# -*- encoding: utf-8 -*-
"""
file       : send_http.py
Date       : 2025/01/09 19:31:11
Author     : Kerry
version    : Rev 0.1
Des:       : 
"""


import base64
import json
import os
import random
import time
import uuid

import requests

# 钧粲推理系统IP地址及端口号
url = "http://127.0.0.1:21000/recv-pic/"

# 发送的图片路径
image_test_path = "/home/adt/CercisFire/RtspTest"

# 发送间隔
send_interval_sec = 1.0


def image_to_base64(image_path):
    with open(image_path, "rb") as img_file:
        return base64.b64encode(img_file.read()).decode("utf-8")


def get_images_path(path):
    files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
    image_files = [f for f in files if f.lower().endswith((".bmp", ".jpg", ".png"))]
    images_path = [os.path.join(path, f) for f in image_files]
    images_path.sort()
    return images_path


files_path = get_images_path(image_test_path)

while True:

    choice_path = random.choice(files_path)

    base64_data = image_to_base64(choice_path)

    area_id = uuid.uuid4().hex

    # 要发送的 JSON 数据
    data = {
        "area_id": area_id,
        "image_data": base64_data,
    }

    # 发送 POST 请求
    try:
        headers = {"Content-Type": "application/json"}  # 设置为 JSON 类型
        response = requests.post(url, data=json.dumps(data), headers=headers)

        # 检查响应状态
        if response.status_code == 200:
            # 打印服务器返回的 JSON 响应
            print(f"数据发送成功：{area_id}", response.json())
        else:
            print(f"发送失败，状态码: {response.status_code}, 响应: {response.text}")

    except requests.exceptions.RequestException as e:
        print("发送过程中出现错误：", e)

    time.sleep(send_interval_sec)
